var _isIE = false, _isIE6 = false, _isIE7 = false, _isIE9 = false, _isNS4 = false, _isNS6 = false, _isWebKit = false, _isFirefox = false;
var MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT;
var NB = {};
if(navigator.appName.indexOf("Microsoft Internet Explorer")!= -1) {
	_isIE = true;
	MOUSE_BUTTON_LEFT = 1;
	MOUSE_BUTTON_RIGHT = 2;
	var __appver = navigator.appVersion.toLowerCase();
	var __iepos = __appver.indexOf("msie");

	if (__iepos != -1) { 
		var is_minor = parseFloat(__appver.substring(__iepos + 5, __appver.indexOf(';', __iepos)));
		_isIE6 = (parseInt(is_minor) <= 6);
		_isIE7 = (parseInt(is_minor) == 7);
		_isIE9 = (parseInt(is_minor) >= 9);
		if(_isIE9) {
			//this may relies on the DOCTYPE of the document
			MOUSE_BUTTON_LEFT = 0;
			MOUSE_BUTTON_RIGHT = 2;
		}
	}
} else if(navigator.appName.indexOf("Netscape") != -1) {
	_isNS6 = true;
	MOUSE_BUTTON_LEFT = 0;
	MOUSE_BUTTON_RIGHT = 2;
} else {
	_isNS4 = true;
	MOUSE_BUTTON_LEFT = 0;
	MOUSE_BUTTON_RIGHT = 2;
}

if(navigator.userAgent.indexOf("WebKit") != -1) {
	_isWebKit = true;
} else if(navigator.userAgent.indexOf("Firefox") != -1) {
	_isFirefox = true;
}

/* *** *** *** *** *** *** *** *** ***
 * this code is taken from http://webfx.eae.net/dhtml/xmlextras/xmlextras.html 
 * *** *** *** *** *** *** *** *** ***
 */
// used to find the Automation server name
function getDomDocumentPrefix() {
	if (getDomDocumentPrefix.prefix)
		return getDomDocumentPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() {
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////


// XmlHttp factory
function XmlHttp() {}

XmlHttp.create = function () {
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}
			
			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method 
if (window.DOMParser) {

	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	//XMLDocument.prototype.loadXML = 
	Document.prototype.loadXML = function (s) {
		
		// parse the string to a new doc	
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		
		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
		/*
		//NOT WORK for chrome 7.0+
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
		*/
		if(doc2.childNodes.length > 0) {
			var rootNode = doc2.childNodes[0];
			var myRoot = this.importNode(rootNode, false);
			this.appendChild(myRoot);
			var childNodes = rootNode.childNodes;
			if(childNodes) {
				for(var i = 0; i < childNodes.length; i++) {
					myRoot.appendChild(this.importNode(childNodes[i], true));
				}
			}
		}
	};
}

// Create xml getter for Mozilla
/* IMPORTANT NOTE
 * Usage of this .xml getter method is deprecated 
 */
if (window.XMLSerializer /*&&
		window.Node && Node.prototype && Node.prototype.__defineGetter__*/) {
	
	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
 	if(!_isIE9 && window.XMLDocument) XMLDocument.prototype.__defineGetter__("xml", function () {
 		return (new XMLSerializer()).serializeToString(this);
 	});
	if(!_isIE9 && window.Document) Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});

	/* doesn't work correctly in mozi */
 	if(!_isIE9 && window.Node) Node.prototype.__defineGetter__("xml", function () {
 		return (new XMLSerializer()).serializeToString(this);
 	});
}

function syncRequest(url, callback) {
	var req = XmlHttp.create();

	req.open("GET", url, false);
	req.send(null);

	if (req.readyState == 4)
	{
		if(callback) {
			var resp = req.responseText;
			callback(resp, req);
		}
	}
}

function asyncRequest(url, callback, cache) {
	var req = XmlHttp.create();
	req.open("GET", url, true);
	if(cache == false) {
		req.setRequestHeader("Cache-Control","no-cache");
		req.setRequestHeader("If-Modified-Since", "0");
	}
	req.onreadystatechange = function()
	{

		if (req.readyState == 4)
		{
			if(callback) {
				var resp = req.responseText;
				callback(resp, req);
			}
		}
	}
	
	req.send(null);
}

function asyncPost(url, params, callback) {
	var req = XmlHttp.create();
	req.open("POST", url, true);
	
	var queryStr = "";
	if(params) {
		for(var pname in params) {
			var pvalue = params[pname];
			//if(pvalue) {
			if(pvalue.constructor == Array) {
				for(var i = 0; i < pvalue.length; i++) {
					queryStr += "&" + pname + "=" + encodeURIComponent(pvalue[i]);
				}
			} else {
				queryStr += "&" + pname + "=" + encodeURIComponent(pvalue);
			}
			//}
		}
		if(queryStr == "") queryStr = "" + params;
		else queryStr = queryStr.substring(1);
	}
	req.setRequestHeader("Content-Length", queryStr.length);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	req.onreadystatechange = function() {
		if (req.readyState == 4)
		{
			if(callback) {
				var resp = req.responseText;
				callback(resp, req);
			}
		}
	}

	req.send(queryStr);
}

function setInnerHTML(element, str) {
	/*
	if(navigator.appName.indexOf("Microsoft Internet Explorer") ==  -1) {
		var r = element.ownerDocument.createRange();
		r.selectNodeContents(element);
		r.deleteContents();
		var df = r.createContextualFragment(str);
		element.appendChild(df);
		
		return str;	
	} else {
	*/
	element.innerHTML = str;
	return str;
	//}
}

function escapeXML(str) {
	if(str == null || str == "")
		return null;

	return str.replace(/&/gm, "&amp;").replace(/</gm, "&lt;").replace(/>/gm, "&gt;").replace(/"/gm, "&quot;");
}

function addEvent(obj, eventName, fn, useCapture) {
	if(_isFirefox && eventName == "mousewheel") eventName = "DOMMouseScroll";
	if(obj.addEventListener) {   
		obj.addEventListener(eventName, fn, useCapture == undefined ? true: useCapture);
		return true;
	} else if(obj.attachEvent) {   
		return obj.attachEvent("on" + eventName, fn);
	} else {
		obj["on" + eventName] = fn; 
	}
}

function removeEvent(obj, eventName, fn, useCapture) {
	if(_isFirefox && eventName == "mousewheel") eventName = "DOMMouseScroll";
	if(obj.addEventListener) {   
		obj.removeEventListener(eventName, fn, useCapture == undefined ? true: useCapture);
		return true;
	} else if(obj.detachEvent) {   
		return obj.detachEvent("on" + eventName, fn);
	} else {
		obj["on" + eventName] = null;
	}
}

function preventDefault(evt) {
	var e = evt || window.event;
	if(e.preventDefault) e.preventDefault();
	else e.returnValue = false;
}

function getPageArea() {
	var __pageSize = getPageSize();
	var __cw = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth;
	PAGE_AREA = {x:parseInt((__cw - __pageSize.width)/2),y:0,width:__pageSize.width,height:__pageSize.height};
	if(!PAGE_AREA.x) {
		var bodycoord = getCoords(document.body);
		PAGE_AREA.x = bodycoord.x;
	}
	return PAGE_AREA;
}

function getWorkArea() {
	var WORK_AREA = {x:null, y:null, width:960, height:null};
	//calculate WORK_AREA
	var __mainnav = document.getElementById("mainnav");
	if(__mainnav) {
		var navcoord = getCoords(__mainnav);
		WORK_AREA.x = navcoord.x;
		WORK_AREA.y = navcoord.y + navcoord.height;
	} else {
		var __header = document.getElementById("header");
		if(__header) {
			var hdcoord = getCoords(__header);
			WORK_AREA.x = hdcoord.x;
			WORK_AREA.y = hdcoord.y + hdcoord.height;
		} else {
			WORK_AREA.y = 0;
			var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
			WORK_AREA.x = (pageWidth > WORK_AREA.width ? (pageWidth - WORK_AREA.width)/2 : 0);
		}
	}

	if(window["NAV_BAR"] != undefined) {
		WORK_AREA.x += NAV_BAR_COORDS.width;
		WORK_AREA.width -= NAV_BAR_COORDS.width;
	}

	var __footer = document.getElementById("footer");
	if(__footer) {
		var __ftcoord = getCoords(__footer);
		WORK_AREA.height = __ftcoord.y - WORK_AREA.y;
	} else {
		var __pageSize = getPageSize();
		WORK_AREA.height = __pageSize.height;
	}

	return WORK_AREA
}

function getCoords(e){
	var left = 0;
	var top  = 0;
	var ww = e.offsetWidth || e.clientWidth;
	var hh = e.offsetHeight || e.clientHeight;
	
	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;
	
	return {x:left, y:top, width:ww, height:hh};
}

/**
*	This function is copied from lightbox.js by Lokesh Dhakar - http://www.huddletogether.com 
*/
function getPageSize() {
		
	 var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return {width:pageWidth,height:pageHeight};
}

function $(name, owner){
	var obj = null;
	if(owner) {
		var elements;
		if(owner.tagName == "FORM") {
			var formElements = document.forms[0].elements;
			if(formElements) {
				elements = new Array();
				for(var i = 0; i < formElements.length; i++) {
					if(formElements[i].name == name) {
						elements[elements.length] = formElements[i];
					}
				}

				if(elements.length == 1) {
					obj = elements[0];
				} else if(elements.length > 0) {
					obj = elements;
				}
			}
		}
	}

	//try id if fails
	if(!obj) obj = document.getElementById(name);
	return obj;
}

function createElement(tagName, name, type) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
	  element = document.createElement("<" + tagName + (name ? " id=\"" + name + "\" name=\"" + name + "\"" : "") + (type ? " type=\"" + type + "\"" : "") + ">");
   } catch (e) {

   }

   if (!element || element.nodeName != tagName.toUpperCase()) {
	  // Non-IE browser; use canonical method to create named element
	  element = document.createElement(tagName);
	  if(name) {
		  element.name = name;
		  element.id = name;
	  }
	  
	  if(type) element.type = type;
   }

   return element;
}

var winhelp;
function openHelp(url, ancname) {
	if(url && ancname) {
		url += "#" + ancname;
	}
	
	if(winhelp && !winhelp.closed) {
		if(url)	winhelp.mainFrame.hload("help/" + url);
	} else {
		winhelp = window.open("help/help.htm" + (url ? "#sec=" + url : ""), "help", "width=960,height=590,resizable=no,scrollbars=no,status=no,menubar=no,toolbar=no,location=no,directories=no");
	}

	if(window.focus) winhelp.focus();
}
var DEFAULT_WIN_WIDTH = 600;
var DEFAULT_WIN_HEIGHT = 450;
function openWindow(url, caption, w, h) {
	var _url, _caption, _width, _height;

	switch(openWindow.arguments.length){
		case 0 :
			break;
		case 1 :
			_url = openWindow.arguments[0];
			break;
		case 2 :
			_url = openWindow.arguments[0];
			_caption = openWindow.arguments[1];
			break;
		case 3 :
			_url = openWindow.arguments[0];
			_width = openWindow.arguments[1];
			_height = openWindow.arguments[2];
			break;
		case 4 :
			_url = openWindow.arguments[0];
			_caption = openWindow.arguments[1];
			_width = openWindow.arguments[2];
			_height = openWindow.arguments[3];
			break;
	}

	if(!_url){
		return;
	}

	if(_caption == ""){
		_caption = "newWin";
	}

	if(!_width){
		_width = DEFAULT_WIN_WIDTH;
	}

	if(!_height){
		_height = DEFAULT_WIN_HEIGHT;
	}
	
    var options = "width=" + _width + ",height=" + _height + ",";
    options += "resizable=yes,scrollbars=yes,status=yes,";
    options += "menubar=no,toolbar=no,location=no,directories=no";
    var newWin = window.open(_url, _caption, options);
    newWin.focus();
}

function enableSelectBlocker(overobj) {
	if(window["__select_blockers"] == undefined) window["__select_blockers"] = new Array();
		var selectBlocker = document.getElementById("__select_blocker");
	var ov_advopt = document.getElementById("overlayer_advopt");
	var ov_task = document.getElementById("overlayer_task");
	var e = overobj;
	var left = 0;
	var top  = 0;
	var ww = e.offsetWidth || e.clientWidth;
	var hh = e.offsetHeight || e.clientHeight;
	
	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
		if(e == ov_advopt){selectBlocker = ov_advopt.lastChild; break;}
		if(e == ov_task){selectBlocker = ov_task.lastChild; break;}
	}

	if(e != ov_advopt && e != ov_task) {
		left += e.offsetLeft;
		top  += e.offsetTop;
	}

	selectBlocker.style.left = left + "px";
	selectBlocker.style.top = top + "px";
	selectBlocker.style.width = ww + "px";
	selectBlocker.style.height = hh + "px";
	selectBlocker.style.visibility = "visible";
	__select_blockers[__select_blockers.length] = selectBlocker;
}

function disableSelectBlocker() {
	if(window["__select_blockers"] != undefined && __select_blockers.length > 0) {
		__select_blockers[__select_blockers.length - 1].style.visibility = "hidden";
		__select_blockers.length--;
	}
}

/**
 * copied from jquery-1.7.1.js
 */
function loadScript(url, callback, scriptCharset) {
	var script;
	var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
	script = document.createElement( "script" );

	script.async = "async";

	if ( scriptCharset ) {
		script.charset = scriptCharset;
	}

	script.src = url;

	// Attach handlers for all browsers
	script.onload = script.onreadystatechange = function( _, isAbort ) {

		if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

			// Handle memory leak in IE
			script.onload = script.onreadystatechange = null;

			// Remove the script
			if ( head && script.parentNode ) {
				head.removeChild( script );
			}

			// Dereference the script
			script = undefined;

			// Callback if not abort
			if ( !isAbort ) {
				callback();
			}
		}
	};
	// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
	// This arises when a base node is used (#2709 and #4378).
	head.insertBefore( script, head.firstChild );
}

function setCookie(name, value, expires, path, domain, secure) { 
    if(!expires){
        expires = 31;
    }

    var expireDate;
    if(!isNaN(expires)){
        expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + expires);
    }else if(expires.toGMTString){
        expireDate = expires;
    }

    document.cookie= name + "=" + escape(value) +
    ((expireDate) ? "; expires=" + expireDate.toGMTString() : "") +
    ((path) ? "; path=" + path : "") + 
    ((domain) ? "; domain=" + domain : "") + 
    ((secure) ? "; secure" : ""); 
} 

function getCookie(name)
{ 
    var dc = document.cookie; 
    var prefix = name + "="; 
    var begin = dc.indexOf("; " + prefix);  
 


    if (begin == -1)
    { 
        begin = dc.indexOf(prefix); 
        if (begin != 0) return null;  
    }
    else
    { 
        begin += 2; 
    } 
    var end = document.cookie.indexOf(";", begin); 
    if (end == -1) 
    { 
        end = dc.length; 
    } 
    
	var value = unescape(dc.substring(begin + prefix.length, end));
	return value;
}

function deleteCookie(name){
	setCookie(name, "", -1);
}

function gotoPage(pageNo, usePost) {
	if(pageNo <= 0) return;

	if (usePost == 1) {
		cp = document.getElementById("curPage");
		if (cp == null) return;
		cp.value = pageNo;
		cp.form.submit();
		return ;
	}
		
	var url = window.location.href;	
	if(url.indexOf("curPage=") == -1) {
		url = url + (url.indexOf("?") == -1 ? "?" : "&") + "curPage=" + pageNo;	
	} else {
		url = url.replace(/curPage=\d*/, "curPage=" + pageNo);
	}

	window.location.href = url;
}

function setPageSize(pageSize, usePost) {
	if(pageSize <= 0) return;
	
	if (usePost == 1) {
		ps = document.getElementById("pageSize");
		if (ps == null) return;
		
		ps.value = pageSize.replace(/[^0-9]/g, "");
		if (ps.value == "") ps.value = "50";
		ps.form.submit();
		return ;
	}
	var url = window.location.href;	
	if(url.indexOf("pageSize=") == -1) {
		url = url + (url.indexOf("?") == -1 ? "?" : "&") + "pageSize=" + pageSize;
	} else {
		url = url.replace(/pageSize=\d*/, "pageSize=" + pageSize);
	}

	window.location.href = url;
}

function parseScriptsAndEval(str) {
	if(str == undefined) return;
	var startIndex;
	var endIndex = -9;
	for(; startIndex != -1 && endIndex != -1; ) { 
		startIndex = str.toLowerCase().indexOf("<script", endIndex + 9);
		if(startIndex == -1) break;

		endIndex = str.toLowerCase().indexOf("</script>", startIndex + 8);
		if(endIndex == -1) break;
		
		if(str.toLowerCase().indexOf("src", startIndex + 7) != -1
				&&  str.toLowerCase().indexOf("src=", startIndex + 7) < str.indexOf(">", startIndex + 7))
		{
				startIndex = str.toLowerCase().indexOf("src=", startIndex + 7);
				var script = str.substring(startIndex + 4, Math.min(str.indexOf(" ", startIndex + 4)==-1?str.indexOf(">", startIndex + 4):str.indexOf(" ", startIndex + 4), str.indexOf(">", startIndex + 4)));
				script = script.replace(/\'|\"/g, '');

				var A = document.createElement("script") , B = document.getElementsByTagName("head")[0];
				A.src = script;
				B.appendChild(A);
		} else {
				startIndex = str.indexOf(">", startIndex + 7);
				if(startIndex >= endIndex) continue;
		
				var script = str.substring(startIndex + 1, endIndex);
				script = script.replace(/^\s*<!--|\/\/-->\s*$/g, '');
				try {
					if(window.execScript) {
						window.execScript(script);
					} else {
						window.eval.call(window, script);
					}
				} catch(exIgnore) {
					//ignore
				}		
		}
	}
}

var __REGEX_DATE = /^(19[7-9]\d|20[0-5]\d)\-(0?\d|1[0-2])\-([0-2]?\d|3[01])(?:\s+(\d{1,2})(?:\:(\d{1,2})(?:\:(\d{1,2}))?)?)?$/;
function parseDate(dateStr) {
	var _date;
	if(__REGEX_DATE.test(dateStr)) {
		var year = RegExp.$1;
		var mon = RegExp.$2;
		var day = RegExp.$3;
		var hr = RegExp.$4;
		var min = RegExp.$5;
		var sec = RegExp.$6;
		_date = new Date(year,mon - 1,day,hr,min,sec);
	} else {
		_date = new Date();
	}

	return _date;
}